import { HttpClient } from '@angular/common/http';
import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Observable, debounce, debounceTime, distinctUntilChanged } from 'rxjs';
// import { CustValidators } from 'src/app/module/me/component/bank-transfer/component/bank-message-confirm/CustValidators';
import { BankTransferService } from 'src/app/service/business/bank-transfer.service';
import { CommonService } from 'src/app/service/common/common.service';
import { MessageService } from 'src/app/service/message.service';
import { UserBindService } from 'src/app/service/user-bind.service';
import { CARD_REG, CORPORATE_CODE_REG, NAME_REG, PHONE_REG } from 'src/app/utils/regExp';

@Component({
  selector: 'app-owner-change',
  templateUrl: './owner-change.component.html',
  styleUrls: ['./owner-change.component.scss']
})
export class OwnerChangeComponent implements OnInit {

  @Input() ownerChangeDataId = '';

  jbrcardPic = [{
    "filter": {
      "method": "GET",
      "data": {
        "filter": [
          {
            "value": "Model.jbrzjbh",
          }
        ],
      },
      "url": "api/gsxmcp/pb/fm/v1.0/getLicencePdf"
    },
    "label": "电子证照验证",
    "type": "asyncRequest"
  }]

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private userBind: UserBindService,
    private bankTransferService: BankTransferService,
    private router: Router,
    private message: MessageService,
    private common: CommonService
  ) { }

  ngOnInit() {
    this.common.setRightInfoVisible(true)

    this.initForm();
    this.initPage();
  }

  validateForm: FormGroup = new FormGroup({});
  bankTransferInfo: FormGroup = new FormGroup({});
  meterInfo: FormGroup = new FormGroup({});
  fileForm: FormGroup = new FormGroup({});
  initForm() {
    this.validateForm = this.fb.group({
      setId: ['4'],
      typeId: ['4'],
      isSecret: true,
      msgWay: ['0dc1cc45-7a35-4241-888c-9f392a5e2f17'],
      customerType: ['', [
        Validators.required
      ]],
      usageCode: ['', [
        Validators.required
      ]],
      // address: [{value: '', disabled: true}, ],
      waterElectric: [false],
      electricNo: [''],
      syrname: ['', [
        Validators.required
      ]],
      syrphone: ['', [
        Validators.required, Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)
      ]],
      syrzjlx: ['', [
        Validators.required
      ]],
      syrzjh: ['', [
        Validators.required
      ]],
      // 申请人电话
      usertel: ['', [ Validators.required, Validators.pattern(PHONE_REG) ]],
      cardType: ['', [ Validators.required ]], // 申请人证件类型
      cardIdNum: ['', [ Validators.required ]], // 申请人证件号

      // 单位
      userName: [''],
      corporateCode: [''],
      jbrname: [''],
      jbrphone: [''],
      jbrzjbh: [''],

      infoSources:'WT',
    });
    this.onUsageCodeChange()
    
    // 文件上传
    this.fileForm = this.fb.group({
      // 文件上传
      syrcardPic: ['', [
        Validators.required
      ]],
      waterSupplyAgreement: [''],
      propertyOwnershipCertificate: ['', [
        Validators.required
      ]],

      // 单位
      jbrcardPic: [''],
      companyApplication: [''],
      balanceAuthPic: [''],
      businessAuthPic: [''],
      corporatePic: [''],

      // 其他
      otherPic: [],

      // 银行划扣
      identityPic: [''],
      accountPic: ['']
    })

    // 银行划扣
    this.bankTransferInfo = this.fb.group({
      dealBankTransfer: [],
      account:['', Validators.required],
      bankId:['', Validators.required],
      bankName: [''],
      bankCode: [''],
      accountName: ['', Validators.required],
      accountCardId: ['', Validators.required],
      accountPhone: ['', [Validators.required, Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)]],
      waterAgreementNo: [''],
      email: [''],
      mailAddress: [''],
      contactPhone: ['', [Validators.required, Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)]]
    }),

    this.meterInfo = this.fb.group({
      meterNum: ['', [
        Validators.pattern(/^[1-9][0-9]{0,5}$/)
      ]],
      // waterPic: ['', Validators.required]
      waterPic: ['']
    })


    this.basicLiveForm = this.fb.group({
      personNum: ['0'],
      basicLiveInfo: this.fb.group({})
    });
  }
  ownerChangeData: any = null;
  uploadAvailable: boolean = true;
  initPage(){
    this._getSyrzjlxList();

    if(this.ownerChangeDataId){
      // 过户详情
      const url = `/api/gsxmcp/cf/mg/v1.0/switchOwner/detail/${this.ownerChangeDataId}`
      this.http.get(url).subscribe(res => {
        this.ownerChangeData = res;
        console.log(this.ownerChangeData)
        this.ownerChangeData.dealBankTransfer = this.ownerChangeData.dealBankTransfer === '1' ? true : false;

        const validateFormData = this.ownerChangeData;
        console.log(validateFormData)
        const fileFormData = {
          // 文件上传
          syrcardPic: validateFormData.syrcardPic,
          waterSupplyAgreement: validateFormData.waterSupplyAgreement,
          propertyOwnershipCertificate: validateFormData.propertyOwnershipCertificate,
          // 单位
          jbrcardPic: validateFormData.jbrcardPic,
          companyApplication: validateFormData.companyApplication,
          balanceAuthPic: validateFormData.balanceAuthPic,
          corporatePic: validateFormData.corporatePic,
          businessAuthPic: validateFormData.businessAuthPic,
          otherPic: validateFormData.otherPic,
          accountPic: validateFormData.accountPic,
          identityPic:  validateFormData.identityPic
        }
        const bankTransferInfoData = {
          dealBankTransfer: validateFormData.dealBankTransfer,
          account: validateFormData.account,
          bankId: validateFormData.bankId,
          bankName:  validateFormData.bankName,
          bankCode:  validateFormData.bankCode,
          accountName:  validateFormData.accountName,
          accountCardId:  validateFormData.accountCardId,
          accountPhone:  validateFormData.accountPhone,
          waterAgreementNo:  validateFormData.waterAgreementNo
        }

        const { waterPic, meterNum } = validateFormData
        this.meterInfo.patchValue({
          waterPic, meterNum
        })

        this.validateForm.patchValue(validateFormData)
        this.fileForm.patchValue(fileFormData)
        this.bankTransferInfo.patchValue(bankTransferInfoData)
        console.log(bankTransferInfoData)

        if(this.ownerChangeData.customerType === '0'){
          const { cuinfo } = this.ownerChangeData;

          this.basicLiveForm?.patchValue({
            personNum: cuinfo.length
          })
          this.personNumChange(cuinfo.length)
          let basicLiveInfoData = {} as any;
          for(let i = 0; i < cuinfo.length; i++){
            basicLiveInfoData[`userName${i}`] = cuinfo[i].userName;
            basicLiveInfoData[`usertel${i}`] = cuinfo[i].userTel;
            basicLiveInfoData[`newCardType${i}`] = cuinfo[i].newCardType;
            basicLiveInfoData[`cardIdNum${i}`] = cuinfo[i].cardIdNum;
            basicLiveInfoData[`cardPic${i}`] = cuinfo[i].cardPic;
          }
          this.basicLiveForm?.get('basicLiveInfo')?.patchValue(basicLiveInfoData);
        }

        this.validateForm.disable()
        this.basicLiveForm?.get('basicLiveInfo')?.disable()
        this.bankTransferInfo.disable()
        this.meterInfo.disable()
        this.uploadAvailable = false
        this.basicLiveForm?.get('personNum')?.disable()

      })
    }
  }

  // 水电联办
  onWaterElectricChange(e: any){
    if(e){
      this.validateForm.get('electricNo')?.setValidators([Validators.required])
      this.validateForm.get('electricNo')?.updateValueAndValidity()
    }else{
      this.validateForm.get('electricNo')?.clearValidators()
      this.validateForm.get('electricNo')?.updateValueAndValidity()
    }
  }

  // 校验 使用人姓名
  syrnameErrorMsg = '';
  syrnameValidator(e: any){
    console.log(e)
    if(!e){
      this.syrnameErrorMsg = '使用人姓名不能为空';
      return true;
    }
    if(/[0-9]/.test(e)){
      this.syrnameErrorMsg = '使用人姓名不能包含 数字';
      return true;
    }
    this.syrnameErrorMsg = '';
    return false
  }
  syrnameBlur(){
    const syrname = this.validateForm.get('syrname')?.value;
    if(syrname.indexOf('住户') > -1 || syrname.indexOf('用户') > -1 || syrname.indexOf('待定') > -1){
      // this.syrnameErrorMsg = '使用人姓名不能包含 "住户","用户"或者"待定"';
      this.message.infoModal('使用人姓名中包含 "住户"、"用户"、"待定", 请确认')
    }
  }

  // TODO 校验 用户编号
  usageCodeValidate = '';
  onUsageCodeChange(){
    this.validateForm.get('usageCode')?.valueChanges.pipe(
      debounceTime(800), distinctUntilChanged()
    ).subscribe(async value => {
      this.usageCodeValidate = 'validating'
      const msg = await this.common.usageCodeValid('4', value)
      if(msg){
        this.message.error(msg, true)
        this.usageCodeValidate = 'error'
        return
      }
      this.usageCodeValidate = 'success'
    })
  }
  

  // 用户类型
  onCustomerTypeChange(type: any){
    if(type === '1'){
      this.validateForm.get('userName')?.setValidators([Validators.required, 
        // CustValidators.maxByteLength(100)
      ]);
      // this.validateForm.get('usertel').setValidators([Validators.required, Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)]);
      this.validateForm.get('corporateCode')?.setValidators([Validators.required, Validators.pattern(CORPORATE_CODE_REG)]);
      this.validateForm.get('jbrname')?.setValidators([Validators.required, Validators.pattern(NAME_REG)]);
      this.validateForm.get('jbrphone')?.setValidators([Validators.required, Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)]);
      this.validateForm.get('jbrzjbh')?.setValidators(Validators.required);

      this.fileForm.get('jbrcardPic')?.setValidators(Validators.required);
      this.fileForm.get('companyApplication')?.setValidators(Validators.required);
      this.fileForm.get('corporatePic')?.setValidators(Validators.required);
      // this.fileForm.get('balanceAuthPic').setValidators(Validators.required);
      this.fileForm.get('businessAuthPic')?.setValidators(Validators.required);
    
      this.bankTransferInfo.get('email')?.setValidators([
        Validators.required,
        Validators.pattern(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/),
        // CustValidators.maxByteLength(40)
      ])
    }else{
      this.fileForm.get('jbrcardPic')?.clearValidators();
      this.fileForm.get('companyApplication')?.clearValidators();
      this.fileForm.get('corporatePic')?.clearValidators();
      // this.fileForm.get('balanceAuthPic').clearValidators();
      this.fileForm.get('businessAuthPic')?.clearValidators();

      this.validateForm.get('userName')?.clearValidators();
      // this.validateForm.get('usertel').clearValidators();
      this.validateForm.get('corporateCode')?.clearValidators();
      this.validateForm.get('jbrname')?.clearValidators();
      this.validateForm.get('jbrphone')?.clearValidators();
      this.validateForm.get('jbrzjbh')?.clearValidators();

      this.bankTransferInfo.get('email')?.setValidators([
        Validators.pattern(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/),
        // CustValidators.maxByteLength(40)
      ])
    }

    this.bankTransferInfo.updateValueAndValidity()
  }

  // 当证件类型为身份证时
  onCardTypeChange(value: string, index: number){
    console.log(value, index)
    const typeName: any = this.cardTypeList.filter((item: any) => item.id === value)
    console.log(typeName)
    if(typeName[0].name === '居民身份证'){
      (this.basicLiveForm?.get('basicLiveInfo') as FormGroup )?.get(`cardIdNum${index}`)?.setValidators([Validators.required, Validators.pattern(CARD_REG)])
    }else{
      (this.basicLiveForm?.get('basicLiveInfo') as FormGroup )?.get(`cardIdNum${index}`)?.setValidators([Validators.required])
    }
    (this.basicLiveForm?.get('basicLiveInfo') as FormGroup )?.get(`cardIdNum${index}`)?.updateValueAndValidity()
  }
  onSyrzjlxChange(value: string){
    const typeName: any = this.cardTypeList.filter((item: any) => item.id === value)
    if(typeName[0].name === '居民身份证'){
      this.validateForm.get('syrzjh')?.setValidators([Validators.required, Validators.pattern(CARD_REG)])
    }else{
      this.validateForm.get('syrzjh')?.setValidators([Validators.required])
    }
    this.validateForm.get('syrzjh')?.updateValueAndValidity()
  }
  
  /************************* 办理银行划扣 *************************/
  waterAgreementNo = '';
  onDealBankTransferChange(e: any){
    if(e){    
      // 文件
      this.fileForm.get('identityPic')?.setValidators(Validators.required)
      this.fileForm.get('accountPic')?.setValidators(Validators.required)
      this.fileForm.get('balanceAuthPic')?.setValidators(Validators.required);
    }else{
      this.fileForm.get('identityPic')?.clearValidators()
      this.fileForm.get('accountPic')?.clearValidators()
      this.fileForm.get('balanceAuthPic')?.clearValidators()
    }
  }

  bankList: any = [];
  codeNumber = '';
  bankIsLoading = false;
  bankSearch(value: string){
    this.bankIsLoading = true;
    this.bankTransferService.getBankList(this.codeNumber, value).subscribe(res => {
      if(res){
        this.bankList = res.resultList;
      }else{
        this.bankList = [];
      }
      this.bankIsLoading = false;
    }, error => {
      console.log(error);
      this.bankIsLoading = false;
      // this.util.createErrorMessage(error);
    });
  }
  onBankChange(value: string){
    this.bankTransferInfo.patchValue({bankCode: '', bankName: ''})
    
    let bank: any = this.bankList.find((item: any) => {
      return item.bankId === value;
    })
    if(bank){
      this.bankTransferInfo.patchValue({ bankCode: bank.bankCode, bankName: bank.bankName })
    }
  }

  pageType = 2; // 2 新增
  modalIsVisible = false;
  nzSpinning = true;
  viewPDF(){
    if(this.ownerChangeData){
      this.modalIsVisible = true;
      this.nzSpinning = true;

      let url = `/api/gsxmcp/pb/fm/v1.0/download/${this.bankTransferInfo.get('waterAgreementNo')?.value}`;
      this._pdfPreview2(url);
    }else{
      if(this._validateForm()){
        this.modalIsVisible = true;
        this.nzSpinning = true;

        this._pdfjs(this._getFormData());
      }else{
        this.message.info('请补充基本信息和银行划扣信息');
      }
      
    }
  }
  _validateForm(){
    this.syrnameValidator(this.validateForm.get('syrname')?.value);

    if(this.usageCodeValidate === 'error') return false

    let flag = true;
    console.log(this.bankTransferInfo.getRawValue())
    if(this.bankTransferInfo.get('dealBankTransfer')?.value){
      let controls1 = this.bankTransferInfo.controls;
      for (let i in controls1) {
        controls1[i].markAsDirty();
        controls1[i].updateValueAndValidity();
      }
      for(let i in controls1){
        if(controls1[i].invalid){
          flag = false ;
          break;
        }
      }
    }
    
    let controls = this.validateForm.controls;
    for (let i in controls) {
      controls[i].markAsDirty();
      controls[i].updateValueAndValidity();
    }
    for(let i in controls){
      if(controls[i].invalid){
        flag = false ;
        break;
      }
    }

    console.log(flag)
    return flag;
  }
  _validateMeterInfo(){
    let flag = true
    
    let controls2 = this.meterInfo.controls;
    for (let i in controls2) {
      controls2[i].markAsDirty();
      controls2[i].updateValueAndValidity();
    }
    for(let i in controls2){
      if(controls2[i].invalid){
        flag = false ;
        break;
      }
    }

    return flag
  }

  _pdfjs(formData: any){
    this.bankTransferService.savePDF(formData).subscribe((res) => {
      let url = `/api/gsxmcp/pb/fm/v1.0/download/${res}`;
      this.waterAgreementNo = res;

      this._pdfPreview2(url);
    }, error => {
      this.nzSpinning = false;
    })
  }
  _pdfPreview2(url: any){
    let f = document.createElement('iframe');
    f.src = 'assets/js/pdfjs/web/viewer.html?file=' + url;
    f.width = '752';
    f.height = '420';

    setTimeout(()=>{
      document.getElementById('pdfpreview')?.appendChild(f);
      
      this.nzSpinning = false;
    }, 0)
  }
  _getFormData(): FormData{
    let formData = new FormData();
    if(this.validateForm.get('customerType')?.value === '0'){
      formData.append('yhlx', 'gryh'); // 用户类型
      formData.append('grzjhm', this.bankTransferInfo.get("accountCardId")?.value);
    }else if(this.validateForm.get('customerType')?.value === '1'){
      formData.append('yhlx', 'dwyh'); // 用户类型
      formData.append('dwzjhm', this.bankTransferInfo.get("accountCardId")?.value);
      formData.append('nsrsbh', this.bankTransferInfo.get("accountCardId")?.value);
    }
    // 用户编号
    formData.append('yhbh', this.validateForm.get("usageCode")?.value);
    formData.append('yhmc', this.validateForm.get("syrname")?.value);
    formData.append('ysdz', this.validateForm.get("address")?.value);

    formData.append('khhmc', this.bankTransferInfo.get("bankName")?.value);
    formData.append('yhhm', this.bankTransferInfo.get("accountName")?.value);
    formData.append('kpmc', this.bankTransferInfo.get("accountName")?.value);
    formData.append('yhzh', this.bankTransferInfo.get("account")?.value);
    formData.append('yhlxsj', this.validateForm.get("syrphone")?.value); // 联系手机

    formData.append('img_sqrqm', this.nameData);

    return formData;
  }
  modalHandleCancel(){
    this.modalIsVisible = false;
  }
  modalHandleOk(){
    if(this.ownerChangeData){
      this.message.info('预览信息不能签署');
      return ;
    }

    this.signModal()
  }
  signModalVisible = false;
  signModal(){
    if(this.pageType === 0){
      this.message.info('预览不支持签署');
      return ;
    }
    this.modalIsVisible = false;
    this.signModalVisible = true;
    setTimeout(() => {
      this._drawName();
    }, 0)
  }
  signModalCancel(){
    this.signModalVisible = false;
  }
  signModalOk(){
    
  }
  canvasWidth: any;
  canvasHeight: any;
  strokeColor: any;
  isMouseDown: any;
  lastLoc: any;
  lastTimestamp: any;
  lastLineWidth: any;
  canvas: any;
  context: any;
  nameData: any;
  isSign = false;
  _drawName(){
    this.canvasWidth = Math.min( 600 , 800 );
    this.canvasHeight = this.canvasWidth;

    this.strokeColor = "black";
    this.isMouseDown = false;
    this.lastLoc = {x:0, y:0};
    this.lastTimestamp = 0;
    this.lastLineWidth = -1;

    this.canvas = document.getElementById("name-canvas");
    this.context = this.canvas.getContext("2d");

    this.canvas.width = this.canvasWidth;
    this.canvas.height = 320;

    let img = new Image();
    img.src = this.nameData;
    img.onload = () => {
      this.context.drawImage(img, 0, 0);
    }
    

    this.canvas.onmousedown = (e: any) => {
      e.preventDefault();
      this.beginStroke( {x: e.clientX , y: e.clientY} );
    };

    this.canvas.onmousemove = (e: any) => {
      e.preventDefault()
      if( this.isMouseDown ){
        this.moveStroke({x: e.clientX , y: e.clientY})
      }
    };

    this.canvas.onmouseup = (e: any) => {
      e.preventDefault()
      this.endStroke()
    };
    this.canvas.onmouseout = (e: any) => {
      e.preventDefault()
      this.endStroke()
    };

  }

  beginStroke(point: any){
    this.isMouseDown = true
    this.lastLoc = this.windowToCanvas(point.x, point.y);
    this.lastTimestamp = new Date().getTime();
  }
  moveStroke(point: any){
    var curLoc = this.windowToCanvas( point.x , point.y );
    var curTimestamp = new Date().getTime();
    // var s = this.calcDistance( curLoc , this.lastLoc )
    // var t = curTimestamp - this.lastTimestamp

    // var lineWidth = this.calcLineWidth( t , s );

    //draw
    this.context.beginPath();
    this.context.moveTo( this.lastLoc.x , this.lastLoc.y );
    this.context.lineTo( curLoc.x , curLoc.y );

    this.context.strokeStyle = this.strokeColor
    this.context.lineWidth = 8
    this.context.lineCap = "round"
    this.context.lineJoin = "round"
    this.context.stroke()

    this.lastLoc = curLoc
    this.lastTimestamp = curTimestamp
    this.lastLineWidth = 8

    this.isSign = true;
  }

  windowToCanvas( x: any , y: any ){
    var bbox = this.canvas.getBoundingClientRect();
    return {x:Math.round(x-bbox.left) , y:Math.round(y-bbox.top)}
  }
  calcDistance( loc1: any , loc2: any ){
    return Math.sqrt( (loc1.x - loc2.x)*(loc1.x - loc2.x) + (loc1.y - loc2.y)*(loc1.y - loc2.y) )
  }

  maxLineWidth = 30;
  minLineWidth = 1;
  maxStrokeV = 10;
  minStrokeV = 0.1;
  calcLineWidth( t: any , s: any ){

    var v = s / t;

    var resultLineWidth;
    if( v <= this.minStrokeV )
        resultLineWidth = this.maxLineWidth;
    else if ( v >= this.maxStrokeV )
        resultLineWidth = this.minLineWidth;
    else{
        resultLineWidth = this.maxLineWidth - (v-this.minStrokeV)/(this.maxStrokeV-this.minStrokeV)*(this.maxLineWidth-this.minLineWidth);
    }

    if( this.lastLineWidth == -1 )
        return resultLineWidth;

    return resultLineWidth*1/3 + this.lastLineWidth*2/3;
  }

  endStroke(){
    this.isMouseDown = false
  }

  clearName(){
    this.context.clearRect( 0 , 0 , this.canvasWidth, this.canvasHeight );
    this.nameData = null;
    this.isSign = false;
  }
  saveName(){
    if(this.isSign){
      this.nameData = this.canvas.toDataURL();

      this.signModalVisible = false;
      this.modalIsVisible = true;
      this.nzSpinning = true;

      // TODOs: 待测试
      this._pdfjs(this._getFormData());
      // this.util.success('保存成功');
    }else{
      this.message.error('请先签名');
    }
  }
  /************************* 办理银行划扣 结束 *************************/

  /************************* 动态添加表单字段 *************************/
  basicLiveForm: FormGroup | any;
  controlArray: Array<{ id: number; controlNames: any[] }> = [];
  personNumChange(e: number): void {
    const id = this.controlArray.length > 0 ? this.controlArray[this.controlArray.length - 1].id + 1 : 0;
    const controlArrayLen = this.controlArray.length;
    if(e > controlArrayLen){ // 增加的情况
      for(let i = 0; i < e - controlArrayLen; i++){
        const controlNames = [
          { label: '姓名', controlName: `userName${id + i}`, type: 'input' },
          { label: '电话', controlName: `usertel${id + i}`, type: 'input' },
          { label: '证件类型', controlName: `newCardType${id + i}`, type: 'select' },
          { label: '证件号码', controlName: `cardIdNum${id + i}`, type: 'input' },
          { label: '身份证明文件', controlName: `cardPic${id + i}`, type: 'upload' }
        ];

        controlNames.forEach(item => {
          const controlName = item.controlName;
          // const index = this.controlArray.push(control);
          
          if(item.controlName.indexOf('usertel') > -1){
            (this.basicLiveForm?.get('basicLiveInfo') as FormGroup ).addControl(
              controlName,
              new FormControl(null, [Validators.required, Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)])
            );
          }else{
            (this.basicLiveForm?.get('basicLiveInfo') as FormGroup ).addControl(
              controlName,
              new FormControl(null, Validators.required)
            );
          }
        })
        
        this.controlArray.push({id: id + i, controlNames})
      }
    }
    if(e < controlArrayLen){ // 数字减少的情况
      console.log(controlArrayLen)
      console.log(id)
      for(let i = 0; i < controlArrayLen - e; i++){
        this.controlArray.pop();

        let index = controlArrayLen - 1 - i;
        const controlNames = [
          { label: '姓名', controlName: `userName${index}`, type: 'input' },
          { label: '电话', controlName: `usertel${index}`, type: 'input' },
          { label: '证件类型', controlName: `newCardType${index}`, type: 'select' },
          { label: '证件号码', controlName: `cardIdNum${index}`, type: 'input' },
          { label: '身份证明文件', controlName: `cardPic${index}`, type: 'upload' }
        ];

        console.log(controlNames)
        console.log((this.basicLiveForm?.get('basicLiveInfo') as FormGroup ))

        controlNames.forEach(item => {
          const controlName = item.controlName;
          (this.basicLiveForm?.get('basicLiveInfo') as FormGroup ).removeControl(controlName);
        })
      }
    }
  }
  removeBasicLiveInfo(item: { id: number; controlNames: Object[] }){
    if(this.ownerChangeDataId) return

    let indenx = this.controlArray.indexOf(item);
    this.controlArray.splice(indenx, 1);
    // this.controlArray.forEach(item => {
    //   console.log(item)
    // })

    item.controlNames.forEach((e: any) => {
      (this.basicLiveForm?.get('basicLiveInfo') as FormGroup ).removeControl(e.controlName);
    })
    this.basicLiveForm?.patchValue({ personNum: this.controlArray.length })
    
  }
  /************************* 动态添加表单字段 end *************************/
  
  cardTypeList: any = []
  cardTypeLoading = false;
  _getSyrzjlxList(){
    this.cardTypeLoading = true;
    this.common.dictQuery('证件类型').subscribe({
      next: res => {
        if(res && res.length > 0){
          // this.cardTypeList = res.filter((item: any) => ['其它', '户口本'].indexOf(item.name) === -1);
          this.cardTypeList = res
        }
        this.cardTypeLoading = false;
      }
    })
  }

  btnLoading = false;
  onSubmit(){
    console.log(this.validateForm)
    console.log(this.fileForm)
    console.log(this.meterInfo)
    console.log((this.basicLiveForm?.get('basicLiveInfo') as FormGroup))
    // if(this.bankTransferInfo.get('dealBankTransfer')?.value){
    //   if(this.waterAgreementNo){
    //     this.bankTransferInfo.patchValue({
    //       waterAgreementNo: this.waterAgreementNo
    //     })
    //   }else{
    //     this.message.info('办理银行划扣需签署业务办理单')
    //     return ;
    //   }
    // }

    // if(this.validateForm.get('customerType')?.value === '0'){
    //   if(this.basicLiveForm?.get('personNum')?.value <= 0){
    //     this.message.info('需要补充新业主信息');
    //     return ;
    //   }
    // }

    // let controls2 = (this.basicLiveForm?.get('basicLiveInfo') as FormGroup).controls;
    // for (let i in controls2) {
    //   controls2[i].markAsDirty();
    //   controls2[i].updateValueAndValidity();
    // }
    // for(let i in controls2){
    //   if(controls2[i].invalid){
    //     return ;
    //   }
    // }


    if(!this._validateForm() || !this._validateFileForm() || !this._validateMeterInfo()){
      return ;
    }

    // 提交
    let params = this.validateForm.getRawValue();
    // params.personNum = this.basicLiveForm.get('personNum').value;
    params.cuinfo = this._getDetailList();

    Object.assign(params, this.bankTransferInfo.getRawValue(), this.meterInfo.getRawValue(), this.fileForm.getRawValue())
    
    if(params.dealBankTransfer){
      params.dealBankTransfer = '1'
    }else{
      params.dealBankTransfer = '0'
    }

    console.log('params =======> ', params);
    this.addBasicLive(params);
  }
  _validateFileForm(){
    let flag = true;

    let fileControls = this.fileForm.controls;
    for (let i in fileControls) {
      fileControls[i].markAsDirty();
      fileControls[i].updateValueAndValidity();
    }
    for(let i in fileControls){
      if(fileControls[i].invalid){
        flag = false;
      }
    }

    return flag;
  }
  _getDetailList(){
    let details = (this.basicLiveForm?.get('basicLiveInfo') as FormGroup).getRawValue();
    let detailList = [];
    for(let i = 0; i < this.basicLiveForm?.get('personNum')?.value; i++){
      if(details.hasOwnProperty(`userName${i}`)){
        let detail = {};
        detail['userName'] = details[`userName${i}`]
        detail['usertel'] = details[`usertel${i}`];
        detail['newCardType'] = details[`newCardType${i}`];
        detail['cardIdNum'] = details[`cardIdNum${i}`];
        detail['cardPic'] = details[`cardPic${i}`];

        detailList.push(detail);
      }
    }

    return detailList;
  }

  // 文件上传回调接口
  uploadBack(fileId: any, fileName: any){
    if(this.fileForm.get(fileName)){
      this.fileForm.get(fileName)?.setValue(fileId);
    }else{
      (this.basicLiveForm?.get('basicLiveInfo') as FormGroup).get(fileName)?.setValue(fileId);
    }
    
  }

  meterUploadBack(fileId: any, fileName: any){
    this.meterInfo.get(fileName)?.setValue(fileId)
  }

  /************************* 接口 *************************/
  getSyrzjlxList(): Observable<any>{
    let url = '/api/gsxmcp/bd/cm/v1.0/codeItems/D002'
    return this.http.get(url);
  }
  addBasicLive(params: any){
    this.btnLoading = true;
    const url = '/api/gsxmcp/cf/mg/v1.0/switchOwner';
    this.http.post(url, params).subscribe(res => {
      console.log(res)
      this.btnLoading = false;
      this.message.successModal('提交成功, 跳转回首页', () => {
        this.router.navigate(['/business-transaction/nav'])
      });
    }, error => {
      console.log(error);
      this.btnLoading = false;
      this.message.createErrorMessage(error);
    })
  }
  validUseageCode(code: string): Observable<any>{
    const url = `/api/gsxmcp/rg/um/v1.0/usageCode?code=${code}`
    return this.http.get(url);  
  }
  /************************* 接口结束 *************************/
  onReset(){
    this.message.confirmModal('确定退出吗？退出将清空表单信息，并返回上一页！', () => {
      history.go(-1)
    })
  }

  goBack(){
    history.go(-1)
  }

  cardIdVerifyBtnBack(e: any, key: any, fieldKey: any){
    if(this.validateForm.get(fieldKey)){
      this.fileForm.get(key)?.setValue(e)
      this.validateForm.get(fieldKey)?.disable()
    }

    if(this.bankTransferInfo.get(fieldKey)){
      this.fileForm.get(key)?.setValue(e)
      this.bankTransferInfo.get(fieldKey)?.disable()
    }

    if((this.basicLiveForm?.get('basicLiveInfo') as FormGroup).get(fieldKey)){
      (this.basicLiveForm?.get('basicLiveInfo') as FormGroup).get(key)?.setValue(e);
      (this.basicLiveForm?.get('basicLiveInfo') as FormGroup).get(fieldKey)?.disable()
    }
  }

}
